package com.liuyi.mybatisplus.gen;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.liuyi.mybatisplus.gen.mapper.TablesMapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 *
 * </p>
 *
 * @author Mr.Fmy
 * @since 2020-10-13
 */
@Controller
@MapperScan("com.liuyi.mybatisplus.gen.mapper")
@Slf4j
public class GenController {

    @Autowired
    private TablesMapper tablesMapper;

    @Value("${spring.datasource.url}")
    @Setter
    private String url;

    @Value("${spring.datasource.username}")
    @Setter
    private String username;

    @Value("${spring.datasource.password}")
    @Setter
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    @Setter
    private String driverClassName;

    public GenController(Environment environment) {
        log.info("代码生成生产环境请勿打开");
        log.info("代码生成请访问：http://localhost:" + environment.getProperty("server.port","8080") + "/liuyi_gen");
    }

    @GetMapping("/liuyi_gen")
    public String index(Model model) {
        model.addAttribute("tables", tablesMapper.listTables());
        return "index";
    }

    @PostMapping("/generate")
    @ResponseBody
    public Boolean generate(com.liuyi.mybatisplus.gen.Model model) {
        try {
            common(dsc -> {
                //数据源配置
                dsc.setUrl(url);
                dsc.setDriverName(driverClassName);
                dsc.setUsername(username);
                dsc.setPassword(password);
            }, model);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return true;
    }

    private void common(Consumer<DataSourceConfig> consumer, com.liuyi.mybatisplus.gen.Model model) throws ClassNotFoundException {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(model.getOutputDir() + File.separator + "java");
        gc.setAuthor(model.getAuthor());
        gc.setOpen(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        gc.setSwagger2(model.isSwagger2());
        gc.setServiceImplName("%sServiceImpl");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        consumer.accept(dsc);
        mpg.setDataSource(dsc);
        // 包配置
        final PackageConfig pc = new PackageConfig();
        if (StrUtil.isNotBlank(model.getModuleName())) {
            pc.setModuleName(model.getModuleName());
        }
        pc.setParent(model.getParent());
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return model.getOutputDir() + "/resources/mapper/" + (StrUtil.isBlank(model.getModuleName()) ? "" : model.getModuleName() + "/") + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        templateConfig.setService("/custService.java.vm");
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityColumnConstant(true);
        strategy.setChainModel(true);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //实体类包对象
        if (StrUtil.isNotBlank(model.getSuperEntityClass())) {
            strategy.setSuperEntityClass(Class.forName(model.getSuperEntityClass()));
        }
        if (StrUtil.isNotBlank(model.getSuperMapperClass())) {
            strategy.setSuperMapperClass(model.getSuperMapperClass());
        }
        //自定义继承的Service类全称，带包名
        if (StrUtil.isNotBlank(model.getSuperServiceClass())) {
            strategy.setSuperServiceClass(model.getSuperServiceClass());
        }
        strategy.setInclude(model.getTables().split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(model.getTablePrefix());
        mpg.setStrategy(strategy);
        mpg.execute();
    }
}
